<template>
  <div id="map"></div>
</template>
<script>
import mapMixin from './mapMixin'
import { getProvince, getCity, getChinaMap, mapAll } from '@/api/index'
import echarts from 'echarts'
export default {
  mixins: [mapMixin],
  props: {
    mapDatas: {
      type: Array,
      default: () => {
        return []
      }
    },
    areaType: {
      type: Number,
      default: 1
    }
  },
  data() {
    return {
      showMap: true,
      myChart: '',
      geoJson: null,
      ID: 0,
      cityCode: 0,
      compareList: []
    }
  },
  mounted() {
    if (this.$store.state.currentArea === 1) {
      this.getChinaMap()
    } else if (this.$store.state.currentArea === 2) {
      this.getProvinceData(this.$store.state.currentProvince)
    } else if (this.$store.state.currentArea === 3) {
      this.getCityData(this.$store.state.currentCity)
    } else {
      this.getCityData(this.$store.state.currentCity)
    }
  },
  methods: {
    // 获取中国地图
    async getChinaMap() {
      try {
        const res = await getChinaMap()
        if (document.querySelector('#map')) {
          this.myChart = echarts.init(document.querySelector('#map'))
          this.geoJson = JSON.stringify(res.data)
          this.initMap(this.geoJson, 'china', this.mapDatas)
        }
      } catch (error) {
        console.log(error)
      }
    },
    async getCityData(code, mapPoints) {
      try {
        const res = await getCity(code)
        if (res.data) {
          if (document.querySelector('#map')) {
            this.myChart = echarts.init(document.querySelector('#map'))
            this.geoJson = JSON.stringify(res.data)
            this.initMap(this.geoJson, code, mapPoints)
          }
        }
      } catch (error) {
        console.log(error)
      }
    },
    async getProvinceData(id, mapPoints) {
      try {
        const res = await getProvince(id)
        if (res.data) {
          this.myChart = null
          if (document.querySelector('#map')) {
            this.myChart = echarts.init(document.querySelector('#map'))
            this.geoJson = JSON.stringify(res.data)
            this.initMap(this.geoJson, id, mapPoints)
          }
        }
      } catch (error) {
        console.log(error)
      }
    },
    // 筛选出所有省份名称
    filterName() {
      this.compareList = []
      this.mapList.forEach((element) => {
        this.compareList.push(element.name)
      })
    },
    initMap(geodata, code, pointsData) {
      if (this.myChart) {
        this.myChart.dispose()
        this.myChart = null
      }
      let pointLists = []
      let scatterPoints = []
      if (pointsData) {
        pointLists = pointsData.map((item) => {
          return {
            id: item.id,
            name: item.name, //item.name,
            value: item.value
            //[item.lng, item.lat, item.value]
          }
        })
        scatterPoints = pointsData.map((item) => {
          return {
            id: item.id,
            name: item.name, //item.name,
            value: [item.lng, item.lat, item.value]
          }
        })
      }
      if (document.querySelector('#map')) {
        this.myChart = echarts.init(document.querySelector('#map'))
        this.myChart.showLoading()

        if (code) {
          echarts.registerMap(code, geodata)
        } else {
          echarts.registerMap(this.ID, geodata)
          this.filterName()
        }
        const option = {
          visualMap: {
            min: 0,
            max: 300000,
            show: true,
            //   text: ['>=1000000', '0'],
            seriesIndex: [1], //必须设置此项,否则会覆盖标注点颜色
            realtime: true,
            calculable: true,
            itemWidth: 8,
            itemHeight: 141,
            right: 50,
            bottom: 100,
            inRange: {
              color: ['#5BB2FF', '#024DA4']
              // color: ['yellow', 'lightskyblue', 'orangered']
            },
            textStyle: {
              color: '#B0CCF8'
            }
          },
          geo: {
            map: code ? code : this.ID,
            roam: true,

            label: {
              normal: {
                show: false,
                textStyle: {
                  color: 'rgba(180, 208, 252, 1)' //省份字体颜色
                }
              },
              emphasis: {
                show: false,
                textStyle: {
                  color: '#B4D0FC'
                }
              }
            },
            itemStyle: {
              normal: {
                borderColor: 'rgba(20, 59, 139, 1)',
                borderWidth: 2,
                areaColor: 'rgba(43, 164, 255, 0.8)'
              },
              emphasis: {
                areaColor: '#0056B3'
              }
            }
          },
          series: [
            {
              roam: true,
              type: 'effectScatter',
              coordinateSystem: 'geo',
              data: scatterPoints,
              // [
              //   {
              //     name: '北京',
              //     value: [117.37778715533908, 40.63949807870581, 199]
              //   }
              // ],
              showEffectOn: 'render',
              rippleEffect: {
                brushType: 'stroke'
              },
              sysmbolSize: 30,
              label: {
                normal: {
                  formatter: '{b}',
                  position: 'right',
                  fontSize: 10,
                  show: true
                }
                // emphasis: {
                // 	show: true,
                // 	areaColor: 'red',
                // 	borderWidth: 0
                // }
              },
              itemStyle: {
                normal: {
                  color: '#96F0FA'
                }
              }
            },
            {
              type: 'map',
              map: 'china',
              data: pointLists,
              geoIndex: 0,
              aspectScale: 0.75, //长宽比
              showLegendSymbol: false, // 存在legend时显示
              label: {
                normal: {
                  show: false
                },
                emphasis: {
                  show: false,
                  textStyle: {
                    color: '#fff'
                  }
                }
              },
              roam: true,
              itemStyle: {
                normal: {
                  areaColor: '#031525',
                  borderColor: '#3B5077'
                }
                // emphasis: {
                // 	areaColor: '#2B91B7'
                // }
              },
              animation: false
              // data: [{
              //     name:14,
              //     value:4000
              // }]
            }
          ]
        }
        this.myChart.clear()
        this.myChart.setOption(option, true)
        this.myChart.hideLoading()
        this.myChart.on('click', (params) => {
          if (scatterPoints.length > 0) {
            this.$parent.showLoading = true
            if (!this.compareList.includes(params.name)) {
              // 点击判断为不是第一次进来
              this.$store.commit('setBeginState', 2)
              let code = this.getCityId(this.geoJson, params.name)
              if (typeof(code) ==='number') {
                code = code.toString()
              }
              if (code.indexOf('0000') !== -1) {
                code = code.substr(0, 2)
              }
              if (code.length === 2) {
                const id = this.mapList.filter((item) => {
                  return item.name.includes(params.name)
                })[0].id
                this.ID = id
                this.$store.commit('setCurrentArea', 2)
                this.$store.commit('setCurrentProvince', Number(id + '0000'))
                this.$parent.getStatisticsListFn(2, this.$store.state.currentProvince)
                this.getProvinceData(id)
                this.$emit('clickProvince', params.name, id)
              }
              if (code.length === 4) {
                code = code + '00'
                // 只下钻到县级别(县级的code是6位数)
                this.getCityData(code)
                this.$store.commit('setCurrentArea', 3) //市级别
                this.$store.commit('setCurrentCity', code)
                this.$emit('clickCity', params.name, code)
                this.$parent.getStatisticsListFn(3, this.$store.state.currentProvince, code)
              } else if (code.length === 6) {
                // 直辖市要另外判断
                const strheader = code.substring(0,3)
                this.$store.commit('setCountyCode', code)
                if(strheader === '110') {
                  this.$store.commit('setCurrentCity', '110100')
                }else if(strheader === '120') {
                  this.$store.commit('setCurrentCity', '120100')
                }else if(strheader === '500'){
                  this.$store.commit('setCurrentCity', '500100')
                }else if(strheader === '310'){
                  this.$store.commit('setCurrentCity', '310100')
                }
                // 海南除去 三亚，海口 也要做特殊判断
                let HaiNanArry = ['469003', '469005', '469033', '469036', '469007', '469006', '469027', '469030', '469002', '469031', '469034', '469026', '469025', '469035', '469001']
                if (HaiNanArry.indexOf(code) !== -1) {
                  this.getCityData(code)
                  this.$store.commit('setCurrentArea', 3) //市级别
                  this.$store.commit('setCurrentCity', code)
                  this.$emit('clickCity', params.name, code)
                  this.$parent.getStatisticsListFn(3, this.$store.state.currentProvince, code)
                } else {
                  this.$store.commit('setCurrentArea', 4) // 县级别
                  this.$store.commit('setCurrentCounty', params.name)
                  this.$emit('clickCounty', params.name)
                  this.$parent.getStatisticsListFn(
                    4,
                    this.$store.state.currentProvince,
                    this.$store.state.currentCity,
                    code
                  )
                }
              }
            }
          }
        })
      }
    },
    async refreshMapByArea(val) {
      switch (this.areaType) {
        case 1:
          await this.getChinaMap()
          break
        case 2:
          await this.getProvinceData(this.$store.state.currentProvince.toString().substr(0, 2), val)
          this.$parent.showLoading = false
          break
        case 3:
          await this.getCityData(this.$store.state.currentCity, val)

          break
        default:
          break
      }
    }
  },
  watch: {
    mapDatas: {
      deep: true,
      handler(val) {
        this.refreshMapByArea(val)
      }
    },
    areaType: {
      deep: true,
      handler(val) {
        if (val !== 4 && val !== 5) {
          if (this.myChart) {
            this.myChart.clear()
            this.myChart.dispose()
            this.myChart = null
          }
        }
      }
    }
  }
}
</script>
<style lang="scss" scoped>
#map {
  flex: 1;
  display: flex;
}
</style>
